<template>
  <div class="websocket-test-container">
    <h2>WebSocket测试页面</h2>
    
    <div class="connection-section">
      <h3>连接控制</h3>
      <div class="connection-controls">
        <el-input 
          v-model="recipient" 
          placeholder="请输入接收者的用户id" 
          style="width: 300px; margin-right: 10px;"
        />
        <el-button 
          @click="connect" 
          :disabled="connectionStatus === 'connected'"
          type="primary"
        >
          连接
        </el-button>
        <el-button 
          @click="disconnect" 
          :disabled="connectionStatus !== 'connected'"
          type="danger"
        >
          断开连接
        </el-button>
      </div>
      <div class="connection-status">
        连接状态: 
        <span 
          :class="{
            'status-connected': connectionStatus === 'connected',
            'status-disconnected': connectionStatus === 'disconnected',
            'status-connecting': connectionStatus === 'connecting'
          }"
        >
          {{ statusText }}
        </span>
      </div>
    </div>

    <div class="message-section">
      <h3>消息测试</h3>
      <div class="message-controls">
        <el-input 
          v-model="messageText" 
          placeholder="请输入消息内容" 
          style="width: 400px; margin-right: 10px;"
        />
        <el-button 
          @click="sendMessage" 
          :disabled="connectionStatus !== 'connected'"
          type="success"
        >
          发送消息
        </el-button>
      </div>
      <div class="message-list">
        <h4>消息记录:</h4>
        <div v-if="messages.length === 0" class="no-messages">暂无消息</div>
        <div v-else class="message-items">
          <div 
            v-for="(msg, index) in messages" 
            :key="index" 
            :class="{
              'message-item': true,
              'message-sent': msg.type === 'sent',
              'message-received': msg.type === 'received',
              'message-system': msg.type === 'system'
            }"
          >
            <span class="message-time">{{ msg.time }}</span>
            <span class="message-type">{{ getMessageTypeText(msg.type) }}:</span>
            <span class="message-content">{{ msg.content }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="advanced-section">
      <h3>高级功能测试</h3>
      <el-button @click="testAutoReconnect" :disabled="connectionStatus !== 'connected'">测试自动重连</el-button>
      <el-button @click="checkConnection" type="info">检查连接状态</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useWebSocketStore } from '../stores/websocket';

// 状态管理
const wsStore = useWebSocketStore();
const token = ref('');
const messageText = ref('');
const recipient = ref('');
const messages = ref([]);
const connectionStatus = ref('disconnected'); // disconnected, connecting, connected
const statusText = ref('未连接');

// 格式化时间
const formatTime = () => {
  const now = new Date();
  return now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 获取消息类型文本
const getMessageTypeText = (type) => {
  switch(type) {
    case 'sent': return '发送';
    case 'received': return '接收';
    case 'system': return '系统';
    default: return '未知';
  }
};

// 连接WebSocket
const connect = () => {
  // recipient.value = token.value;
  token.value = localStorage.getItem('token');
  if (!recipient.value.trim()) {
    ElMessage.warning('请输入接收者的用户id');
    return;
  }

  try {
    connectionStatus.value = 'connecting';
    statusText.value = '连接中...';
    wsStore.connect(token.value);
    
    // 模拟连接状态更新
    setTimeout(() => {
      if (wsStore.ws && wsStore.ws.readyState === WebSocket.OPEN) {
        connectionStatus.value = 'connected';
        statusText.value = '已连接';
        addSystemMessage('WebSocket连接成功！');
      }
    }, 1000);

    // 监听消息事件
    setupMessageListeners();
  } catch (error) {
    connectionStatus.value = 'disconnected';
    statusText.value = '连接失败';
    addSystemMessage(`连接失败: ${error.message}`);
  }
};

// 设置消息监听器
const setupMessageListeners = () => {
  if (!wsStore.ws) return;

  // 保存原始的onmessage处理函数
  const originalOnMessage = wsStore.ws.onmessage;
  
  // 重写onmessage处理函数
  wsStore.ws.onmessage = (event) => {
    // 调用原始的处理函数
    originalOnMessage(event);
    
    // 处理消息并显示在界面上
    try {
      const data = JSON.parse(event.data);
      addReceivedMessage(JSON.stringify(data, null, 2));
    } catch (error) {
      addReceivedMessage(event.data);
    }
  };

  // 监听连接关闭事件
  wsStore.ws.onclose = (event) => {
    connectionStatus.value = 'disconnected';
    statusText.value = '已断开连接';
    addSystemMessage(`连接已关闭: 代码 ${event.code}, 原因: ${event.reason}`);
  };

  // 监听错误事件
  wsStore.ws.onerror = (error) => {
    addSystemMessage(`WebSocket错误: ${error.message || '未知错误'}`);
  };
};

// 断开连接
const disconnect = () => {
  wsStore.disconnect();
  connectionStatus.value = 'disconnected';
  statusText.value = '已断开连接';
  addSystemMessage('已手动断开连接');
};

// 发送消息
const sendMessage = () => {
  if (!messageText.value.trim()) {
    ElMessage.warning('请输入消息内容');
    return;
  }

  try {
    const messageObj = {
        sender: 'chf',
        recipient: recipient.value, // 接收者的用户id
        content: messageText.value,
        type: 'text',
        timestamp: new Date().getTime() // 时间搓 
        // msg: messageText.value
    };
    wsStore.send(messageObj);
    addSentMessage(JSON.stringify(messageObj, null, 2));
    messageText.value = '';
  } catch (error) {
    addSystemMessage(`发送失败: ${error.message}`);
  }
};

// 测试自动重连
const testAutoReconnect = () => {
  addSystemMessage('测试自动重连功能...');
  // 这里可以添加自动重连的测试逻辑
};

// 检查连接状态
const checkConnection = () => {
  const state = wsStore.ws ? wsStore.ws.readyState : -1;
  let stateText = '';
  
  switch(state) {
    case WebSocket.CONNECTING: stateText = '连接中 (CONNECTING)'; break;
    case WebSocket.OPEN: stateText = '已连接 (OPEN)'; break;
    case WebSocket.CLOSING: stateText = '关闭中 (CLOSING)'; break;
    case WebSocket.CLOSED: stateText = '已关闭 (CLOSED)'; break;
    default: stateText = '未初始化'; break;
  }
  
  ElMessage.info(`当前连接状态: ${stateText}`);
  addSystemMessage(`连接状态检查: ${stateText}`);
};

// 添加发送消息
const addSentMessage = (content) => {
  messages.value.push({
    type: 'sent',
    content,
    time: formatTime()
  });
  scrollToBottom();
};

// 添加接收消息
const addReceivedMessage = (content) => {
  messages.value.push({
    type: 'received',
    content,
    time: formatTime()
  });
  scrollToBottom();
};

// 添加系统消息
const addSystemMessage = (content) => {
  messages.value.push({
    type: 'system',
    content,
    time: formatTime()
  });
  scrollToBottom();
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const messageList = document.querySelector('.message-items');
    if (messageList) {
      messageList.scrollTop = messageList.scrollHeight;
    }
  }, 100);
};

// 组件挂载时
onMounted(() => {
  addSystemMessage('WebSocket测试页面已加载');
});

// 组件卸载时
onUnmounted(() => {
  // 确保断开连接
  if (connectionStatus.value === 'connected') {
    disconnect();
  }
});
</script>

<style scoped>
.websocket-test-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.connection-section,
.message-section,
.advanced-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fafafa;
}

.connection-controls {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.connection-status {
  font-size: 14px;
  color: #606266;
}

.status-connected {
  color: #67c23a;
  font-weight: bold;
}

.status-disconnected {
  color: #f56c6c;
}

.status-connecting {
  color: #e6a23c;
}

.message-controls {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.message-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  height: 400px;
  background-color: #fff;
  overflow-y: auto;
}

.no-messages {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.message-items {
  height: 360px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
}

.message-sent {
  background-color: #f0f9ff;
  border-left: 4px solid #409eff;
}

.message-received {
  background-color: #f0f0f0;
  border-left: 4px solid #67c23a;
}

.message-system {
  background-color: #fefce8;
  border-left: 4px solid #e6a23c;
}

.message-time {
  color: #909399;
  font-size: 12px;
  margin-right: 10px;
}

.message-type {
  font-weight: bold;
  margin-right: 5px;
}

.message-content {
  word-break: break-all;
  white-space: pre-wrap;
}

.advanced-section {
  display: flex;
  gap: 10px;
}
</style>